package com.mcb_wxc.service;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayUtil;
import com.mcb_wxc.entity.TAgentWx;
import com.mcb_wxc.entity.TWxPay;
import com.mcb_wxc.http.HttpRequester;
import com.mcb_wxc.http.HttpRespons;
import com.mcb_wxc.mapper.TAgentWxMapper;
import com.mcb_wxc.mapper.TWxPayMapper;
import com.mcb_wxc.util.CodeUtil;
import com.mcb_wxc.util.IPUtil;
import com.mcb_wxc.util.ReturnJsonResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 小生
 * 2019/4/13 11:30.
 */
@Api(tags = "WWPAY", description = "微信支付")
@RestController
@RequestMapping(value="/wxPayService")
public class WxPayService {
    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;
    @Autowired
    TAgentWxMapper tAgentWxMapper;
    @Autowired
    TWxPayMapper tWxPayMapper;

    private static final String APPID = "wxfd753794e86d02d8";
    private static final String APPSECRET = "f2d78f39bc9f0bb9c2b415c25ae3773d";


    @ApiOperation(value="getWxOpenId", notes="通过code查询微信用户openid" , httpMethod = "GET", response = WxPayService.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code",value = "code",required = true,dataType = "String",paramType="query"),
    })
    @GetMapping("/getWxOpenId")
    public String getWxOpenId(String code){
        ReturnJsonResultUtil result = new ReturnJsonResultUtil();
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try{
            if(code == null) {
                result.setResultCode(CodeUtil.FAIL);
                result.setContent("参数错误！");
                return result.toString();
            }
            //获取appid和secret
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+APPID+"&secret="+APPSECRET+"&js_code="+code+"&grant_type=authorization_code";
            HttpRequester http = new HttpRequester();
            HttpRespons respons = http.sendGet(url);
            JSONObject jsonObject = JSONObject.parseObject(respons.getContent()); // 转换成JSONObject对象
            Map<String, Object> datamap = jsonObject;

            TAgentWx tAgentWx = new TAgentWx();
            tAgentWx.setOpenid(datamap.get("openid")+"");
            List<TAgentWx> tAgentWxs = tAgentWxMapper.select(tAgentWx);
            if(tAgentWxs == null || tAgentWxs.size() == 0) {
                tAgentWx.setIsAuth(0);
                tAgentWxMapper.insert(tAgentWx);
                resultMap.put("userInfo", tAgentWx);
            }else {
                resultMap.put("userInfo", tAgentWxs.get(0));
            }
            resultMap.put("wxInfo", datamap);
            result.setMainData(resultMap);
        }catch (Exception e) {
            result.printLog(request,e);
            result.setResultCode(CodeUtil.FAIL);
            result.setContent(CodeUtil.SERVER_ERROR);
        }
        return result.toString();
    }


    @ApiOperation(value="getParameter", notes="获取微信支付参数" , httpMethod = "GET", response = WxPayService.class)
    @RequestMapping(value = "/getParameter" , method = RequestMethod.GET)
    public String getParameter() {
        ReturnJsonResultUtil result = new ReturnJsonResultUtil();
        //用户openid
        String openid = "o6B0c0cq0eDcv_3ZgqkvPY-GGXdE";
        //金额 实际支付的订单金额:单位 分
        String totalFee = "1";
        //支付名称
        String body = "微信中的支付宝中的京东钱包支付";
        //商品订单编号
        String nonceStr  = WXPayUtil.generateNonceStr();

        try{
            Map<String, String> data = new HashMap<String, String>();
            data.put("appid", "wxfd753794e86d02d8");
            data.put("mch_id", "1226127602");
            data.put("nonce_str", nonceStr); //uuid
            data.put("body", body); //支付名称
            data.put("out_trade_no", nonceStr); //保持唯一就行
            data.put("total_fee", "1"); //表示一份钱
            String spbillCreateIp = IPUtil.getRemoteIp(request);//IP地址
            data.put("spbill_create_ip", spbillCreateIp);
            data.put("notify_url", "http://hu.suhucg.com:9258/wxc/wxPayService/paymentCallback"); //回调地址
            data.put("trade_type", "JSAPI"); //表示小程序支付
            data.put("openid", openid);
            //获取签名
            String sign = WXPayUtil.generateSignature(data,"PmADGwX82e8lWU8bPmADGwX82e8lWxfj");
            data.put("sign", sign);

            String xml = WXPayUtil.mapToXml(data);//将所有参数(map)转xml格式

            // 统一下单 https://api.mch.weixin.qq.com/pay/unifiedorder
            String unifiedorder_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            HttpRequester http = new HttpRequester();
            String xmlStr = http.sendPost(unifiedorder_url, xml);//发送post请求"统一下单接口"返回预支付id:prepay_id

            //以下内容是返回前端页面的json数据
            String prepay_id = "";//预支付id
            if (xmlStr.indexOf("SUCCESS") != -1) {
                Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
                prepay_id = (String) map.get("prepay_id");
            }
            Map<String, String> payMap = new HashMap<String, String>();
            payMap.put("appId", "wxfd753794e86d02d8");
            payMap.put("timeStamp", System.currentTimeMillis()/1000 + "");
            payMap.put("nonceStr", WXPayUtil.generateNonceStr());
            payMap.put("signType", "MD5");
            payMap.put("package", "prepay_id=" + prepay_id);
            String paySign = WXPayUtil.generateSignature(payMap, "PmADGwX82e8lWU8bPmADGwX82e8lWxfj");
            payMap.put("paySign", paySign);

            //添加待支付的记录
            TWxPay tWxPay = new TWxPay();
            BigDecimal amountPay = (new BigDecimal(totalFee).divide(new BigDecimal("100"))).setScale(2);//将分转换成元-实际支付金额:元
            tWxPay.setPayBody(body);
            tWxPay.setPayTotalFee(amountPay);
            tWxPay.setPayOutTradeNo(nonceStr);
            tWxPay.setPayOpenid(openid);
            tWxPay.setPayStatic("0");
            tWxPay.setPayCreateTime(new Date());
            tWxPayMapper.insert(tWxPay);
            result.setMainData(payMap);
        }catch (Exception e) {
            result.printLog(request,e);
            result.setResultCode(CodeUtil.FAIL);
            result.setContent(CodeUtil.SERVER_ERROR);
        }
        return result.toString();
    }



    @ApiOperation(value="paymentCallback", notes="支付回调" , httpMethod = "POST", response = WxPayService.class)
    @RequestMapping(value = "/paymentCallback" , method = RequestMethod.POST)
    public String paymentCallback() {
        ReturnJsonResultUtil result = new ReturnJsonResultUtil();
        InputStream is = null;
        try{
            is = request.getInputStream();//获取请求的流信息(这里是微信发的xml格式所有只能使用流来读)
            System.out.println("is----------------------" + is);
            String xml = inputStreamToString(is);
            System.out.println("xml----------------------" + xml);
            Map<String, String> notifyMap = WXPayUtil.xmlToMap(xml);//将微信发的xml转map
            System.out.println("notifyMap----------------------" + notifyMap);
            //添加待支付的记录
            String ordersSn = notifyMap.get("out_trade_no");//商户订单号
            System.out.println("ordersSn---------------------" + ordersSn.toString());
            TWxPay tWxPay = new TWxPay();
            tWxPay.setPayOutTradeNo(ordersSn);
            List<TWxPay> tWxPays = tWxPayMapper.select(tWxPay);
            System.out.println("tWxPays---------------------" + tWxPays.toString());
            if(tWxPays == null || tWxPays.size() == 0) {
                result.setResultCode(CodeUtil.FAIL);
                result.setContent("订单号无效");
                return result.toString();
            }
            tWxPay = tWxPays.get(0);
            System.out.println("tWxPay---------------------" + tWxPay);
            //业务处理
            if(notifyMap.get("return_code").equals("SUCCESS")){
                if(notifyMap.get("result_code").equals("SUCCESS")){
                    tWxPay.setPayStatic("1");
                    tWxPay.setPayUpdateTime(new Date());
                    System.out.println("成功了---------------------" + notifyMap.get("return_code"));
                }
            }else {
                //业务处理
                tWxPay.setPayStatic("2");
                tWxPay.setPayUpdateTime(new Date());
                System.out.println("失败了---------------------" + notifyMap.get("return_code"));
            }
            tWxPayMapper.updateByPrimaryKey(tWxPay);
            //告诉微信服务器收到信息了，不要在调用回调action了========这里很重要回复微信服务器信息用流发送一个xml即可
            response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>");
            is.close();
        }catch (Exception e) {
            result.printLog(request,e);
            result.setResultCode(CodeUtil.FAIL);
            result.setContent(CodeUtil.SERVER_ERROR);
        }
        return result.toString();
    }

    /**
     * inputStream转String
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static String inputStreamToString(InputStream inputStream) throws IOException {

        StringBuffer out = new StringBuffer();

        byte[] b = new byte[1024];
        for(int n;(n = inputStream.read(b)) != -1;){
            out.append(new String(b, 0, n));
        }

        if(inputStream != null){
            inputStream.close();
        }

        return out.toString();

    }

}
